package com.baoteng.rbspy.util;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;


public class JsonUtils {

	public static ObjectMapper getObjectMapper() {
		ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		return mapper;
	}

	public static String toJsonString(Object object) {
		try {
			return getObjectMapper().writeValueAsString(object);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	public static void writeJsonString(Object object, Writer writer) {
		try {
			getObjectMapper().writeValue(writer, object);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	public static <T> T parseJson(String jsonString, Class<T> classType) {
		try {
			return getObjectMapper().readValue(jsonString, classType);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static <T> T parseJson(String jsonString,
			TypeReference<T> typeReference) {
		try {
			return getObjectMapper().readValue(jsonString, typeReference);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static <T> T parseJsonT(String jsonString) {
		try {
			return getObjectMapper().readValue(jsonString,
					new TypeReference<Object>() {
					});
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static <T> Map<?, ?> bean2Map(Object bean) {
		try {
			return getObjectMapper().convertValue(bean, Map.class);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static <T> T map2Bean(Map<?, ?> map, Class<T> clazz) {
		try {
			return getObjectMapper().convertValue(map, clazz);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

}
